import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize OpenAI client
client = OpenAI(
    api_key=os.getenv("LLM_API_KEY"),
    base_url=os.getenv("LLM_BASE_URL"),
)

import markdown2

def generate_recipe(ingredients, cuisine, cook_time, difficulty, nutrition_pref):
    prompt = f"Create a creative recipe using these ingredients: {ingredients}. Cuisine style: {cuisine}. Cooking time: {cook_time}, Difficulty: {difficulty}, Nutrition focus: {nutrition_pref}. Include detailed ingredients list, step-by-step instructions, serving suggestions, approximate cooking time, and nutritional information (calories, macros if possible)."
    try:
        response = client.chat.completions.create(
            model=os.getenv("LLM_MODEL"),
            messages=[{"role": "user", "content": prompt}],
            max_tokens=800,
        )
        recipe = response.choices[0].message.content.strip()
        # Convert to HTML for better formatting
        recipe_html = markdown2.markdown(recipe)
        return recipe_html
    except Exception as e:
        return f"抱歉，无法生成食谱。请检查食材输入，如果问题持续，请稍后再试。错误详情：{str(e)}"

# 自定义界面使用Blocks添加加载效果
with gr.Blocks(theme="soft", title="AI 食谱生成器 (优化的创意食谱)") as iface:
    gr.Markdown("# AI 食谱生成器 (优化的创意食谱)")
    gr.Markdown("输入食材、选择偏好，生成详细且营养丰富的食谱。")
    gr.Markdown("提示：食谱包含材料清单、步骤、营养信息和建议。支持复制输出以便分享。")

    with gr.Row():
        ingredients = gr.Textbox(label="食材 (Ingredients)", placeholder="输入可用食材，用逗号分隔，如鸡肉、蔬菜、米饭", lines=2)
        cuisine = gr.Dropdown(
            label="菜系风格 (Cuisine Style)",
            choices=["中餐 (Chinese)", "西餐 (Western)", "意大利 (Italian)", "墨西哥 (Mexican)", "日本 (Japanese)"],
            value="中餐 (Chinese)"
        )
    with gr.Row():
        cook_time = gr.Dropdown(
            label="烹饪时间 (Cooking Time)",
            choices=["快速 (15-30分钟)", "中等 (30-60分钟)", "慢炖 (1小时以上)"],
            value="中等 (30-60分钟)"
        )
        difficulty = gr.Dropdown(
            label="难度级别 (Difficulty Level)",
            choices=["初级 (Beginner)", "中级 (Intermediate)", "高级 (Advanced)"],
            value="初级 (Beginner)"
        )
        nutrition_pref = gr.Dropdown(
            label="营养偏好 (Nutrition Focus)",
            choices=["均衡 (Balanced)", "低脂 (Low-fat)", "高蛋白 (High-protein)", "素食 (Vegetarian)", "无偏好 (None)"],
            value="均衡 (Balanced)"
        )

    with gr.Row():
        generate_btn = gr.Button("生成食谱")
        clear_btn = gr.Button("清除")
        status = gr.Textbox("状态", show_label=False, interactive=False, value="")

    output = gr.HTML(label="生成的食谱 (Generated Recipe)")

    # 示例
    gr.Examples(
        examples=[
            ["鸡肉,洋葱,胡萝卜", "中餐 (Chinese)", "中等 (30-60分钟)", "初级 (Beginner)", "均衡 (Balanced)"],
            ["意大利面,番茄,橄榄油", "意大利 (Italian)", "快速 (15-30分钟)", "中级 (Intermediate)", "高蛋白 (High-protein)"],
            ["牛肉,豆子,玉米", "墨西哥 (Mexican)", "慢炖 (1小时以上)", "高级 (Advanced)", "素食 (Vegetarian)"]
        ],
        inputs=[ingredients, cuisine, cook_time, difficulty, nutrition_pref]
    )

    def clear_all():
        return gr.update(value=""), gr.update(value="中餐 (Chinese)"), gr.update(value="中等 (30-60分钟)"), gr.update(value="初级 (Beginner)"), gr.update(value="均衡 (Balanced)"), gr.update(value=""), gr.update(value="")

    def on_generate(ingredients, cuisine, cook_time, difficulty, nutrition_pref):
        yield ("", "正在生成食谱...")
        recipe = generate_recipe(ingredients, cuisine, cook_time, difficulty, nutrition_pref)
        yield (recipe, "")

    generate_btn.click(
        on_generate,
        inputs=[ingredients, cuisine, cook_time, difficulty, nutrition_pref],
        outputs=[output, status]
    )

    clear_btn.click(
        clear_all,
        inputs=None,
        outputs=[ingredients, cuisine, cook_time, difficulty, nutrition_pref, output, status]
    )

if __name__ == "__main__":
    iface.launch()
